<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-09
 * Time: 16:54
 */

namespace app\service;


use app\api\controller\Goods;
use think\Db;
use think\Exception;
use app\common\model\Express;
use app\common\model\Address;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\ChatMsg as ChatMsgModel;
use app\common\model\MoneyLog as MoneyLogModel;
use app\common\model\GoodsSku as GoodsSkuModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\OrderRecharge;
use app\common\model\Mall;

use GuzzleHttp\Client;
/**
 * 订单信息
 * Class OrderService
 * @package app\service
 */
class OrderService extends BaseService
{
    public $orderModel;
    public function __construct()
    {
        $this->orderModel=new OrderModel();
    }

    /**
     * 查询订单信息
     * @param $where
     * @param $filed
     * @return array|bool
     */
    public function findOrder($where,$filed=null){
        try{
            $detail = $this->orderModel->field($filed)->where($where)->find();
            if($detail) {
                return $detail->toArray();
            }
            return false;
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 订单生成给管理员发模板消息
     * @param $make_order
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    protected function sendTmp($make_order)
    {
        $order_manager = explode(',', config('order_manager'));
        if ($order_manager) {
            //模板消息通知用户
            $send_data['first'] = "客户生成订单";
            $send_data['time'] = $make_order['create_time'];
            $send_data['name'] = $make_order['title'];
            $send_data['order_sn'] = $make_order['order_sn'];
            $send_data['remark'] = "订单生成";
            foreach ($order_manager as $value) {
                $userInfo = \app\common\model\User::getOne(array('id' => $value));
                MsgService::S(["mall_id" => $userInfo['mall_id']])->sendTemp(MsgService::$tempType_NEW_ORDER, $userInfo['mall_id'], $value, $send_data, "");
            }
        }

    }

    /**查询订单信息
     * @param $where
     * @param $page
     * @param int $page_num
     * @param null $filed
     * @return array|bool
     */
    public function selectOrder($where,$page,$page_num=20,$filed=null){
        try{
            return $this->orderModel
                ->order('id desc')
                ->field($filed)
                ->where($where)
                ->page($page,$page_num)
                ->select()
                ->toArray();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**查询订单信息
     * @param $where
     * @param $page
     * @param int $page_num
     * @param null $filed
     * @return array|bool
     */
    public function orderList($where,$filed=null){
        try{
            return $this->orderModel
                ->order('id desc')
                ->field($filed)
                ->where($where)
                ->select()
                ->toArray();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 查询订单数量
     * @param $where
     * @return bool|int|string
     */
    public function countOrder($where){
        try{
            return $this->orderModel->where($where)->count();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 添加订单
     * @param $add
     * @return bool|false|int
     */
    public function addOrder($add){
        try{
            return $this->orderModel->insertGetId($add);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 修改订单信息
     * @param $data
     * @param $where
     * @return false|int
     */
    public function saveOrder($data,$where){
       return $this->orderModel->save($data,$where);
    }

    /**
     * @param $order
     * @param $pay_type  1.微信 2.支付宝 3.站内币
     * @param null $xml_arr
     * @param null $alipayArr
     * @return bool
     */
    public function changeOrder($order,$saveData=false){
        try{
            if(empty($order)){
                return false;
            }

            $where = array(
                "id" => $order['id']
            );
            //已支付
            if($order['checked'] == 1){
                //无需再次支付
                return false;
            }
            if(!$saveData || !$saveData['checked']) {
                $saveData = [
                    'checked' => 1
                ];
            }



            $saveData['pay_time'] = time();
            $order_res = self::saveOrder($saveData,$where);//OrderService::S()->s;//$this->orderModel->editOrder($where, $order_data);

            $this->sendTmp($order);

            if(!$order_res){
                return false;//更改状态失败
            }
             //扣除虚拟币 
             $userInfo = UserModel::getOne(['id'=>$order['uid']]);
             if($order['score_money']>0) {
                 UserModel::changeMoney ($userInfo['id'],2,-$order['score_money'],$content='支付订单扣除',$order);
             }
             if($order['yongjin_money']>0) {
                 UserModel::changeMoney ($userInfo['id'],1,-$order['yongjin_money'],$content='支付订单扣除',$order);
             }
             if($order['cash_money']>0) {
                 UserModel::changeMoney ($userInfo['id'],3,-$order['cash_money'],$content='支付订单扣除',$order);
             }
            $userInfo =UserService::S()->findUser(array('id'=>$order['uid']));//获取用户信息

            //聊天室消息
            $goodsList = json_decode($order['goods_list'],true);

//            ChatMsgModel::create([
//                'uid' => $order['uid'],
//                'content' => json_encode([
//                    'type' => 'message',
//                    'content' => [
//                        'type' => 'buy',
//                        'content' => $order['title'],
//                        'nickname' => $userInfo['nickname'],
//                        'goods_id' => $goodsList[0]['id'],
//                        'uid' => $order['uid']
//                    ]
//                ]),
//                'status' => 0,
//                'type' => 'buy',
//                'mall_id' => $userInfo['mall_id'],
//                'group_id' => UserModel::getGroupId($order['uid'])
//            ]);

            $goods_info =json_decode($order['goods_list'],true) ;//($order['goods']);
            $jinhuo_nums = 0;
            foreach ($goods_info as $k=>$v){
                //更改商品销量,库存
                if($v['sku_id']) {
                    GoodsService::S()->incGoodsFiled($v['id'],'sale_real',$v['goods_num']);
                    GoodsSkuModel::where('id',$v['sku_id'])->setDec('stock',$v['goods_num']);
                }else{
                    GoodsService::S()->incGoodsFiled($v['id'],'sale_real',$v['goods_num']);
                    GoodsService::S()->incGoodsFiled($v['id'],'stock',$v['goods_num'],'desc');
                }
                $jinhuo_nums += $v['goods_num'];
            }
            if(empty($userInfo)){
                return false;
            }
            //检查拼团完成没
            if($order['main_order_id']&&$order['shop_type']==1) {
                $this->checkMainOrder($order['uid'],$order['main_order_id']);
            }
            if($order['shop_type']==4) {
                OrderModel::where('id',$order['id'])->update([
                    'grade_id'=>$goods_info[0]['grade']
                ]);
            }
            //结算佣金
            ThirdService::S()->processing($order['id']);
            return true;//返回真
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }



    /* 发货操作 */
    public function sendOrder ($orderInfo,$data) {

        //扣除积分商城的积分金额
        $goods=json_decode($orderInfo['goods_list'],true);
        $score_money=0;
        foreach ($goods as $k=>$v){
            $score_money+=$v['money_dikou']*$v['goods_num'];
        }
        if($score_money>0) {
            $score_money -= $orderInfo['yongjin_money'];
            $mallInfo = Mall::getOneById($orderInfo['mall_id']);
            if($mallInfo['money']<$score_money) {
                return '该分公司货款不足，请联系负责人充值';
            }
    
            //扣商品库存日志
            $add['money']=$score_money;//$input['money'];
            $add['mall_id']=$orderInfo['mall_id'];//$this->mall_id;
            // $add['mall_name']=['mall_name'];
            $add['create_time']=date('Y-m-d H:i:s');
            $add['remark']='购买商品扣除分公司存款';//$input['remark'];
            $add['order_id']=$order_id;
            $add['order_sn']=$orderInfo['order_sn'];
            $add['log_type']=2;
            $re=OrderRecharge::create($add);
            if($re->id){
                Mall::where(array('id'=>$orderInfo['mall_id']))->setDec('money',$score_money);
            }
        }
        

        $save = [
            'express_com' => $data['express_com'],
            'express_no' => $data['express_no'],
        ];
        if($orderInfo['checked']==1) {
            $save['checked'] = 5;
            $save['send_time'] = time();
        }
        $res = $this->orderModel->where(['id'=>$orderInfo['id']])->update($save);
        return $res?$res:'无任何修改';
    }

    /* 物流信息 */
    function getWuliu($danhao,$com){
        //http://www.aikuaidi.cn/api/?type=2
        $company = array(
            "中通快递" => "zhongtong",
            "圆通快递" => "yuantong",
            "顺丰快递" => "shunfeng",
            "韵达快递" => "yunda",
            "EMS" => "ems",
            "申通快递" => "shentong",
            "天天快递" => "tiantian",
            "优速快递" => "yousu",
            "汇通快递" => "huitong",
            "德邦快递" => "debang",
            "天地华宇" => "tdhy",
            "国通快递" => "guotong",//EDN
            "宅急送快递" => "zjs",
            "安能物流" => "anwl",
            "DHL快递" => "dhl",
            "FEDEX国际快递" => "fedex",
            "FEDEX国内快递" => "fedexcn",
            "广东ems快递" => "gdems",
            "京东快递" => "jingdong",
            "佳吉快运" => "jiaji",
            "龙邦快递" => "longbang",
            "全峰快递" => "quanfeng",
            "如风达快递" => "rufengda",		
            "新邦物流" => "xinbang",
            "安捷快递" => "aj",
            "高铁速递" => "gtsd",
            "日日顺物流" => "rrs",
            "速尔快递" => "suer",
            "UPS国际快递" => "ups",
            "万象物流" => "wxwl",
            "信丰物流" => "xfwl",
            "增益快递" => "zengyi",
            "中铁快运" => "zhongtie",
        );
        $keyes = array(
            "6e5b5c0400594a6b9a703dfb1615a968","e8fb760e1dcb457c8ca3a17801beca48","3ab217fd0b3b401e9a4ce10dd098cd9e"
        );
        $res =cache($com.$danhao);
        if($res){
           return $res; 
        }
        shuffle($keyes);
        $key = $keyes[0];
        $wuliu = $company[$com];
        if(empty($wuliu)){
            return false;
        }
        $url = sprintf('http://www.aikuaidi.cn/rest/?key=%s&order=%s&id=%s&ord=desc&show=json',$key,$danhao,$wuliu);
        $client = new Client();
        $response = $client->get($url);
        $json = (string)($response->getBody());
        if($json){
            $res  = json_decode($json,true);
            if($res['errCode'] != 3){
                //结果缓存30分钟 $danhao,$com
                if($res['status'] == 4){
                    //已经签收,永久缓存
                    cache($com.$danhao, $res);
                }else{
                    cache($com.$danhao, $res, 1800);
                }
                return $res;
            }
        }
        return false;
    }

    /* 检查主订单是否可以拼团 */
    public function checkMainOrder ($uid,$order_id) {
        $orderInfo = OrderModel::getOne(['id'=>$order_id]);
        if(!$orderInfo) {
            return '该订单不存在';
        }
        if($orderInfo['is_end']) {
            return '该订单已拼团结束';
        }
        if(!in_array($orderInfo['checked'],[1,2,5])) {
            return '订单未支付';
        }
        $userInfo = UserModel::getOne(['id'=>$uid]);
        if($userInfo['refer_id']!=$orderInfo['uid']) {
            return '您无法参与该拼团';
        }
        $orderCount = OrderModel::getCount([
            'main_order_id' => $order_id,
            'checked'=> ['in',[1,2,5]]
        ]);
        if(($orderCount+1)>=config('pin_number_goods')) {
            OrderModel::where([
                'id' => $order_id
            ])->update(['is_end'=>1]);
            //结算拼三免一
            ThirdService::S()->pinEnd($orderInfo['id']);
            return  '该订单已拼团结束';
        }
        return true;
    }

    /* 拼团详情 */
    public function pintuanInfo ($order_id) {
        $orderInfo = OrderModel::getOne(['id'=>$order_id]);
        if($orderInfo['main_order_id']!=$order_id) {
            //return false;
        }
        $list = OrderModel::getAll("(main_order_id={$order_id} or id={$order_id}) and checked in (1,2,5)",'id asc','uid');
        if(!$list) {
            return false;
        }
        foreach($list as $k=>$v) {
            $userInfo = UserModel::getOne(['id'=>$v['uid']],'nickname,headimgurl');
            $list[$k]['nickname'] = $userInfo['nickname'];
            $list[$k]['headimgurl'] = $userInfo['headimgurl'];
        }
        return $list;
    }

    /**
     * 查询订单数量
     * @param $where
     * @param $filed
     * @return bool|int|string
     */
    public function sumOrder($where,$filed){
        try{
            return $this->orderModel->where($where)->sum($filed);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /* 订单退款 */
    public function refundOrder ($order_id) {
        $orderInfo = OrderModel::getOneById($order_id);
        $userInfo = UserModel::getOneById($orderInfo['uid']);
        if(!$orderInfo || !in_array($orderInfo['checked'],[1,2,5])) {
            return '当前订单状态不支持退款';
        }
        if($orderInfo['pay_type']==1) {
            //微信支付
            $res = false;
            $res = PayService::S(['mall_id'=>$orderInfo['mall_id']])->wechatRefund($orderInfo);
        }elseif($orderInfo['pay_type']==2) {
            $res = true;
        }

        if(!$res) {
            return '退款失败';
        }
        //修改订单状态
        $manager = session('manager');
        OrderModel::where('id',$order_id)->update([
            'checked' => 4,
            'refund_time' => time(),
            'refund_manager' => $manager['name']
        ]);

        //扣除订单相关佣金
        $logList = MoneyLogModel::getAll([
            'order_id'=>$order_id,
            'log_type' => 1
        ]);
        if($logList) {
            foreach($logList as $log) {
                UserModel::changeMoney($log['uid'],$log['type'],-$log['money'],'[订单退款扣除]'.$log['content'],$orderInfo);
            }
        }

        //退回相关虚拟币
        if($orderInfo['yongjin_money']) {
            UserModel::changeMoney($userInfo['id'],1,$orderInfo['yongjin_money'],'订单退款',$orderInfo);
        }
        if($orderInfo['score_money']) {
            UserModel::changeMoney($userInfo['id'],2,$orderInfo['score_money'],'订单退款',$orderInfo);
        }
        if($orderInfo['cash_money']) {
            UserModel::changeMoney($userInfo['id'],3,$orderInfo['cash_money'],'订单退款',$orderInfo);
        }

        //扣销量
        $goods_info =json_decode($orderInfo['goods_list'],true) ;
        foreach ($goods_info as $k=>$v){
            //更改商品销量,库存
            if($v['sku_id']) {
                GoodsModel::where('id',$v['id'])->setDec('sale_real',$v['goods_num']);
                GoodsSkuModel::where('id',$v['sku_id'])->setInc('stock',$v['goods_num']);
            }else{
                GoodsModel::where('id',$v['id'])->setDec('sale_real',$v['goods_num']);
                GoodsModel::where('id',$v['id'])->setInc('stock',$v['goods_num']);
            }
        }

        $rechargeLog = OrderRecharge::getOne([
            'order_id' => $orderInfo['id'],
            'log_type' => 2
        ]);
        if($rechargeLog) {
            $newLog = $rechargeLog;
            unset($newLog['id']);
            $newLog['log_type'] = 1;
            $newLog['remark'] = '用户退款，返还分公司存款';
            $re=OrderRecharge::create($newLog);
            if($re->id){
                Mall::where(array('id'=>$orderInfo['mall_id']))->setInc('money',$newLog['money']);
            }
        }
       
       

        return true;
    }
}